import { createStore } from "vuex";

export const AUTHENTICATE = "authenticate";
export const UN_AUTHENTICATE = "unAuthenticate";
export const TOKEN = "token";
export const TOKEN_HEAD = "tokenHead";
export const TOKEN_USER_ID = "userId";
export const IS_AUTHENTICATED = "isAuthenticated";

export default createStore({
  state: {
    token: "",
    tokenHead: "",
    userId: "",
  },
  mutations: {
    [AUTHENTICATE]: (state, { token, tokenHead, user }) => {
      state.token = token;
      state.tokenHead = tokenHead;
      state.userId = user && user.id;
      localStorage.setItem("token", token);
      localStorage.setItem("tokenHead", tokenHead);
      localStorage.setItem("userId", user && user.id);
    },
    [UN_AUTHENTICATE]: (state) => {
      state.token = "";
      state.tokenHead = "";
      state.userId = "";
      localStorage.setItem("token", "");
      localStorage.setItem("tokenHead", "");
      localStorage.setItem("userId", "");
    },
  },
  getters: {
    [IS_AUTHENTICATED]: (state) => {
      const token = state.token || localStorage.getItem("token");
      const userId = state.userId || localStorage.getItem("userId");
      return token != null && token != "" && userId != null && userId != "";
    },
    [TOKEN]: (state) => {
      return state.token || localStorage.getItem("token");
    },
    [TOKEN_HEAD]: (state) => {
      return state.tokenHead || localStorage.getItem("tokenHead");
    },
    [TOKEN_USER_ID]: (state) => {
      return state.userId || localStorage.getItem("userId");
    },
  },
  actions: {},
  modules: {},
});
